package javamobile.billsplit;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;

import java.io.File;
import java.io.IOException;

import android.media.MediaRecorder;
import android.os.Environment;

public class AddAudioActivity extends Activity {
	public static final String PREFS_NAME = "MyPrefsFile";
	final MediaRecorder recorder = new MediaRecorder(); 
	private String path; 
	boolean started = false;
	
	private String sanitizePath(String path) {
	    if (!path.startsWith("/")) {
	      path = "/" + path;
	    }
	    if (!path.contains(".")) {
	      path += ".3gp";
	    }
	    return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
	}
	
	public void start() throws IOException {
	    String state = android.os.Environment.getExternalStorageState();
	    if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
	        throw new IOException("SD Card is not mounted.  It is " + state + ".");
	    }

	    // make sure the directory we plan to store the recording in exists
	    File directory = new File(path).getParentFile();
	    if (!directory.exists() && !directory.mkdirs()) {
	      System.out.println("Path to file could not be created.");
	    }

	    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
	    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
	    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
	    recorder.setOutputFile(path);
	    recorder.prepare();
	    recorder.start();
	  }
	
	public void stop() throws IOException {
	    recorder.stop();
	    recorder.release();
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    	SharedPreferences.Editor editor = settings.edit();
    	editor.putString("sound", path);
    	editor.commit();
	    finish();
	  }
	
    @SuppressLint("SdCardPath")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.add_audio); 
        
        path = "recording"; 
        path = sanitizePath(path);  
        
        ImageButton recordButton = (ImageButton) findViewById(R.id.record_btn_ADDAUDIO); 
        recordButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				try {
					if (!started) {
						start(); 
						started = true;
					}
					else {
						stop();
						started = false;
					}
				} catch(Exception e) {
					System.out.println("Exception"); 
					e.printStackTrace();
				}
			}
		});  
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.add_audio, menu);
        return true; 
    }
}
